package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.MockRoomRepo;
import model.Room;
import model.RoomRepo;
import model.User;
import model.Vote;

/**
 * Servlet implementation class VoteServlet
 */
public class VoteServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
   * @see HttpServlet#HttpServlet()
   */
  public VoteServlet() {
    super();
    // TODO Auto-generated constructor stub
  }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO aca hay que procesar el nuevo voto (el usuario esta en la sesion)
    // despues hay que ir a roomServlet por post!
    Boolean status = true;
    RequestDispatcher dispacher;

    if (request.getSession() != null) {
      User u = (User) request.getSession().getAttribute("loggeduser");
      if (u == null) {
        status = false;
        request.setAttribute("error", "You must be logged in to vote!");
      } else {
        String answerName = (String) request.getParameter("q");
        String roomName = (String) request.getParameter("room");

        RoomRepo rooms = MockRoomRepo.getInstance();
        Room room = rooms.getRoom(roomName);
        Vote.AnswerType answer = null;
        if (answerName.equals("A")) {
          answer = Vote.AnswerType.A;
        } else {
          answer = Vote.AnswerType.B;
        }

        Vote vote = new Vote(u, answer);
        room.getLastRound().addVote(vote);
        

      }
    }

    

    request.setAttribute("status", status);
    dispacher = getServletContext().getRequestDispatcher("/vote.jsp");
    dispacher.forward(request, response);
  }

}
